package com.tuniu.agents.common.listener;

import com.tuniu.agents.common.message.MessageSenderManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ConversationStopListener {

    @Autowired
    private MessageSenderManager messageSenderManager;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        // Subscribe to the channel
        container.addMessageListener((message, pattern) -> {
            String conversationId = new String(message.getBody());
            handleStopConversation(conversationId);
        }, new ChannelTopic("channel:stop_conversation"));

        return container;
    }

    /**
     * Handle the stop conversation event
     */
    private void handleStopConversation(String conversationId) {
        log.info("Received stop conversation notification, cleaning up conversation ID: {}", conversationId);

        // Clean up local conversation resources
        boolean localCleanupSuccess = messageSenderManager.stopConversation(conversationId);
        if (localCleanupSuccess) {
            log.info("Node successfully cleaned up conversation ID: {}", conversationId);
        } else {
            log.warn("Node did not find conversation ID: {}", conversationId);
        }
    }
}
